﻿/// <reference path="D:\PROJECTS\eking\Modules\eSeller\Scripts\jcanvas.min.js" />
/// <reference path="D:\PROJECTS\eking\Modules\Orchard.jQuery\Scripts\jquery-1.6.4.min.js" />

var delta = 10;

$(function () {
    $('.menuBtn').menu({
        content: $('#menucontent').html(), // grab content from this page
        showSpeed: 200,
        width: $('#menuBar').css('width')
    });

    showHideRuler($(this).is(':checked'));

    $('#showRuler').click(function () {
        showHideRuler($(this).is(':checked'));
    });

    function showHideRuler(isShow) {
        drawRuler(!isShow);
    }

    installjQueryPlugin();


    function installjQueryPlugin() {

        $(".selectable").selectable(
    {
        filter: 'div'
    });

        $(".resizable").resizable({
            stop: function (event, ui) {
                correctSizePos(this);
            }
        });

        $('.scroll-pane').jScrollPane({ showArrows: true });

        $(".draggable").draggable(
    {
        scroll: true,
        stop: function (event, ui) {
            correctSizePos(this);
        }
    });

    }


    function correctSizePos(input) {

        var val = parseInt($(input).css("left").replace("px", ""));
        $(input).css("left", Math.round(val / delta) * delta + "px");

        val = parseInt($(input).css("top").replace("px", ""));
        $(input).css("top", Math.round(val / delta) * delta + "px");

        val = parseInt($(input).css("width").replace("px", ""));
        $(input).css("width", Math.round(val / delta) * delta + "px");

        val = parseInt($(input).css("height").replace("px", ""));
        $(input).css("height", Math.round(val / delta) * delta + "px");
    }

    $('.rate').rater({ postHref: '/eseller/SellerMain/RateProduct', rating: $(this).attr('data-initVal') });

    var currentSelectProduct = undefined;

    $(".product").click(function () {
        return;
        if (currentSelectProduct != undefined) {
            $(currentSelectProduct).removeClass("product-selected");
        }
        if (currentSelectProduct == this) {
            $(currentSelectProduct).removeClass("product-selected");
            currentSelectProduct = undefined;
            return;
        }
        $(this).addClass("product-selected");
        currentSelectProduct = this;
    });


    $('#modeSwitch').click(function () {
        switchMode();
    });
    switchMode();


    $('#auto').click(function () {
        arrange();
    });

    $('.menu-main').remove();

    $('#deleteSelected').click(function () {
        $.ajax({
            url: "/eSeller/SellerMain/DeleteProduct",
            type: "POST",
            data: JSON.stringify({ id: $(currentSelectProduct).attr('data-Id') }),
            contentType: "application/json; charset=utf-8",
            fail: function () {
                alert('FAIL');
            },
            error: function () {
                alert('ERROR');
            },
            success: function () {
                $(currentSelectProduct).remove();
            }
        });
    });

    $('#addProduct').click(function () {
        $.ajax({
            url: "/eSeller/SellerMain/AddProduct",
            type: "POST",
            data: 'Hero',
            contentType: "application/json; charset=utf-8",
            fail: function () {
                alert('FAIL');
            },
            error: function () {
                alert('ERROR');
            },
            success: function (evt) {
                $('#uiDataContainer').append(evt);
                installjQueryPlugin();
            }
        });
    });


});

var mode = "edit";
function switchMode() {
    mode = mode == "edit" ? "view" : "edit";
    if (mode == "edit") {
        $('#editTools').css("visibility", "visible");
    }
    if (mode == "view") {
        $('#editTools').css("visibility", "hidden");
    }
    if (mode == "edit")
        $('#modeSwitch').html("View");
    else
        $('#modeSwitch').html("Edit");
}

getUiData = function (item) {
    return {
        X: $(item).css("left").replace("px", ""),
        Y: $(item).css("top").replace("px", ""),
        Width: $(item).css("width").replace("px", ""),
        Height: $(item).css("height").replace("px", "")
    }
}

function saveUiData() {
    var tags = $('.product');
    var products = [tags.length];
    for (var i = 0; i < tags.length; i++) {
        products[i] = {
            Id: $(tags[i]).attr("data-Id"),
            UiData: getUiData(tags[i])
        };
    }

    tags = $('.category');
    var categories = [tags.length];
    for (var i = 0; i < tags.length; i++) {
        categories[i] = {
            Id: $(tags[i]).attr("data-Id"),
            UiData: getUiData(tags[i])
        };
    }

    var model = { Id: 10, Products: products, ProductCategories: categories };

    $.ajax({
        url: "/eSeller/SellerMain/SavePosition",
        type: "POST",
        dataType: "json",
        data: JSON.stringify(model),
        contentType: "application/json; charset=utf-8"

    });
}

function arrange() {
    var x = 0;
    var y = 2;
    //var pWidth = 150;
    var pWidth = 230;
    var pHeight = 150;
    var itemSpace = 10;
    var catSpace = 90;
    $(".category").each(function () {
        $(this).css("left", x);
        $(this).css("top", y);
        y = y + 40;
        var yb = y;
        var catId = $(this).attr("data-Id");
        var itemCounter = 0;
        var pendingAddWidth = false;
        $(".product").each(function () {
            var itemCatId = $(this).attr("data-CatId");
            if (itemCatId == catId) {
                if (pendingAddWidth == true) {
                    x = x + pWidth + itemSpace;
                    pendingAddWidth = false;
                }
                itemCounter = itemCounter + 1;
                $(this).css("left", x + "px");
                $(this).css("top", y + "px");
                $(this).css("width", pWidth + "px");
                $(this).css("height", pHeight + "px");
                y = y + pHeight + itemSpace;
                if (itemCounter % 3 == 0) {
                    y = yb;
                    pendingAddWidth = true;
                }
            }
        });
        x = x + pWidth + catSpace;
        y = 2;

    });
}

function drawRuler(clear) {
    $('canvas').attr('width', 3000);
    $('canvas').attr('height', 1000);
    var width = $('canvas').width();
    var height = $('canvas').height();
    var ctx = $('canvas')[0].getContext('2d');

    ctx.clearRect(0, 0, width, height);
    if (clear)
        return;


    ctx.strokeStyle = "red";
    ctx.lineWidth = 0.1;

    var start = 0;

    while (start < width) {
        ctx.strokeLine(start, 0, start, height);
        start += delta;
    }

    start = 0;
    while (start < height) {
        ctx.strokeLine(0, start, width, start);
        start += delta;
    }
}

CanvasRenderingContext2D.prototype.strokeLine = function (x1, y1, x2, y2) {
    this.beginPath();
    this.moveTo(x1, y1);
    this.lineTo(x2, y2);
    this.closePath();
    this.stroke();
}